package com.clouddms.controller;

import com.clouddms.entity.Admin;
import com.clouddms.entity.FileInfo;
import com.clouddms.entity.Backup;
import com.clouddms.entity.User;
import com.clouddms.entity.UserOperationLog;
import com.clouddms.entity.FileOperationLog;
import com.clouddms.repository.AdminRepository;
import com.clouddms.service.storage.BackupService;
import com.clouddms.service.storage.FileService;
import com.clouddms.service.lifecycle.LifecycleService;
import com.clouddms.service.auth.UserService;
import com.clouddms.service.common.ServiceManager;
import com.clouddms.service.common.LogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 管理员API控制器
 * 提供系统管理和监控接口
 */
@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "*", maxAge = 3600)
@PreAuthorize("hasRole('ADMIN') or hasRole('ROOT_ADMIN')")
public class AdminApiController {

    private static final Logger logger = LoggerFactory.getLogger(AdminApiController.class);

    @Autowired
    private ServiceManager serviceManager;

    @Autowired
    private UserService userService;

    @Autowired
    private FileService fileService;

    @Autowired
    private BackupService backupService;

    @Autowired
    private LifecycleService lifecycleService;

    @Autowired
    private LogService logService;

    @Autowired
    private AdminRepository adminRepository;

    /**
     * 获取系统概览信息
     */
    @GetMapping("/dashboard")
    public ResponseEntity<Map<String, Object>> getDashboard() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 用户统计
            UserService.UserStats userStats = userService.getUserStats();
            
            // 文件统计
            FileService.SystemStorageStats storageStats = fileService.getSystemStorageStats();
            
            // 备份统计
            BackupService.BackupStats backupStats = backupService.getBackupStats();
            
            // 生命周期统计
            LifecycleService.LifecycleStats lifecycleStats = lifecycleService.getLifecycleStats();
            
            // 服务状态
            Map<String, Object> serviceStatus = serviceManager.getServiceStatusSummary();
            
            Map<String, Object> dashboard = new HashMap<>();
            dashboard.put("userStats", userStats);
            dashboard.put("storageStats", storageStats);
            dashboard.put("backupStats", backupStats);
            dashboard.put("lifecycleStats", lifecycleStats);
            dashboard.put("serviceStatus", serviceStatus);
            
            response.put("success", true);
            response.put("data", dashboard);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取系统概览失败", e);
            response.put("success", false);
            response.put("message", "获取系统概览失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取服务状态
     */
    @GetMapping("/services")
    public ResponseEntity<Map<String, Object>> getServices() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<Map<String, Object>> services = serviceManager.getAllServiceInfo();
            
            response.put("success", true);
            response.put("data", services);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取服务状态失败", e);
            response.put("success", false);
            response.put("message", "获取服务状态失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 手动执行备份任务
     */
    @PostMapping("/backup/{fileId}")
    public ResponseEntity<Map<String, Object>> createBackup(@PathVariable Long fileId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            BackupService.BackupResult result = backupService.manualBackup(fileId);
            
            response.put("success", result.isSuccess());
            response.put("message", result.getMessage());
            if (result.getBackup() != null) {
                response.put("backup", result.getBackup());
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("创建备份失败", e);
            response.put("success", false);
            response.put("message", "创建备份失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 手动执行清理任务
     */
    @PostMapping("/cleanup")
    public ResponseEntity<Map<String, Object>> executeCleanup() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 执行清理任务
            lifecycleService.cleanupDeletedFiles();
            
            response.put("success", true);
            response.put("message", "清理任务已执行");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("执行清理任务失败", e);
            response.put("success", false);
            response.put("message", "执行清理任务失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取系统中的所有文件
     */
    @GetMapping("/files")
    public ResponseEntity<Map<String, Object>> getAllFiles() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<FileInfo> allFiles = fileService.getAllFiles();
            
            // 转换为包含上传者信息的响应格式
            List<Map<String, Object>> fileResponses = allFiles.stream()
                    .map(this::buildAdminFileInfoResponse)
                    .collect(java.util.stream.Collectors.toList());
            
            response.put("success", true);
            response.put("data", fileResponses);
            response.put("total", fileResponses.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取系统文件失败", e);
            response.put("success", false);
            response.put("message", "获取系统文件失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取系统回收站中的所有文件
     */
    @GetMapping("/trash")
    public ResponseEntity<Map<String, Object>> getAllTrashFiles() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<FileInfo> trashFiles = fileService.getAllDeletedFiles();
            
            response.put("success", true);
            response.put("data", trashFiles);
            response.put("total", trashFiles.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取系统回收站文件失败", e);
            response.put("success", false);
            response.put("message", "获取系统回收站文件失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 管理员恢复文件
     */
    @PostMapping("/trash/restore/{fileId}")
    public ResponseEntity<Map<String, Object>> adminRestoreFile(@PathVariable Long fileId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Optional<FileInfo> fileOpt = fileService.getFileById(fileId);
            if (!fileOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "文件不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            FileInfo file = fileOpt.get();
            boolean success = fileService.restoreFile(fileId, file.getUserId());
            
            if (success) {
                response.put("success", true);
                response.put("message", "文件恢复成功");
                logger.info("管理员恢复文件: fileId={}, userId={}", fileId, file.getUserId());
            } else {
                response.put("success", false);
                response.put("message", "文件恢复失败");
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("管理员恢复文件失败", e);
            response.put("success", false);
            response.put("message", "文件恢复失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 管理员永久删除文件
     */
    @DeleteMapping("/trash/{fileId}")
    public ResponseEntity<Map<String, Object>> adminPermanentDeleteFile(@PathVariable Long fileId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Optional<FileInfo> fileOpt = fileService.getFileById(fileId);
            if (!fileOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "文件不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            FileInfo file = fileOpt.get();
            boolean success = fileService.permanentDeleteFile(fileId, file.getUserId());
            
            if (success) {
                response.put("success", true);
                response.put("message", "文件永久删除成功");
                logger.info("管理员永久删除文件: fileId={}, userId={}", fileId, file.getUserId());
            } else {
                response.put("success", false);
                response.put("message", "文件永久删除失败");
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("管理员永久删除文件失败", e);
            response.put("success", false);
            response.put("message", "文件永久删除失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取备份配置
     */
    @GetMapping("/backup/config")
    public ResponseEntity<Map<String, Object>> getBackupConfig() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Map<String, Object> config = backupService.getBackupConfig();
            
            response.put("success", true);
            response.put("data", config);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取备份配置失败", e);
            response.put("success", false);
            response.put("message", "获取备份配置失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 更新备份配置
     */
    @PutMapping("/backup/config")
    public ResponseEntity<Map<String, Object>> updateBackupConfig(@RequestBody Map<String, Object> config) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean success = backupService.updateBackupConfig(config);
            
            if (success) {
                response.put("success", true);
                response.put("message", "备份配置更新成功");
                logger.info("管理员更新备份配置: {}", config);
            } else {
                response.put("success", false);
                response.put("message", "备份配置更新失败");
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("更新备份配置失败", e);
            response.put("success", false);
            response.put("message", "更新备份配置失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取所有备份列表
     */
    @GetMapping("/backup/list")
    public ResponseEntity<Map<String, Object>> getAllBackups() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<Backup> backups = backupService.getAllBackups();
            
            response.put("success", true);
            response.put("data", backups);
            response.put("total", backups.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取备份列表失败", e);
            response.put("success", false);
            response.put("message", "获取备份列表失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    // ===========================================
    // 用户管理相关接口
    // ===========================================

    /**
     * 获取所有用户列表（包含管理员和普通用户）
     */
    @GetMapping("/users")
    public ResponseEntity<Map<String, Object>> getAllUsers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String search) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<Map<String, Object>> allUsers = new ArrayList<>();
            
            // 获取普通用户
            List<User> users;
            if (search != null && !search.trim().isEmpty()) {
                users = userService.searchUsers(search);
            } else {
                users = userService.getAllUsers();
            }
            
            // 转换普通用户数据
            for (User user : users) {
                Map<String, Object> userMap = new HashMap<>();
                userMap.put("userId", user.getUserId());
                userMap.put("username", user.getUsername());
                userMap.put("password", "***");
                userMap.put("email", user.getEmail());
                userMap.put("createdAt", user.getCreatedAt());
                userMap.put("updatedAt", user.getUpdatedAt());
                userMap.put("isActive", user.getIsActive());
                
                // 设置用户角色
                List<String> roles = new ArrayList<>();
                if (user.getRoles() != null && !user.getRoles().isEmpty()) {
                    roles.addAll(user.getRoles().stream().map(Enum::name).collect(Collectors.toList()));
                } else {
                    roles.add("USER");
                }
                userMap.put("roles", roles);
                userMap.put("admin", false);
                userMap.put("rootAdmin", false);
                userMap.put("userType", "USER");
                
                allUsers.add(userMap);
            }
            
            // 获取管理员用户
            List<Admin> admins = adminRepository.findAll();
            for (Admin admin : admins) {
                Map<String, Object> adminMap = new HashMap<>();
                // 保持原始管理员ID，通过userType区分类型
                adminMap.put("userId", admin.getAdminId());
                adminMap.put("username", admin.getUsername());
                adminMap.put("password", "***");
                adminMap.put("email", admin.getEmail());
                adminMap.put("createdAt", admin.getCreatedAt());
                adminMap.put("updatedAt", admin.getUpdatedAt());
                adminMap.put("isActive", true); // 管理员默认激活
                
                // 设置管理员角色
                List<String> roles = new ArrayList<>();
                if ("system".equals(admin.getUsername())) {
                    roles.add("ROOT_ADMIN");
                    adminMap.put("admin", true);
                    adminMap.put("rootAdmin", true);
                    adminMap.put("userType", "ROOT_ADMIN");
                } else {
                    roles.add("ADMIN");
                    adminMap.put("admin", true);
                    adminMap.put("rootAdmin", false);
                    adminMap.put("userType", "ADMIN");
                }
                adminMap.put("roles", roles);
                
                allUsers.add(adminMap);
            }
            
            // 如果有搜索条件，进一步过滤管理员
            if (search != null && !search.trim().isEmpty()) {
                String searchTerm = search.trim().toLowerCase();
                allUsers = allUsers.stream()
                    .filter(user -> {
                        String username = (String) user.get("username");
                        String email = (String) user.get("email");
                        return (username != null && username.toLowerCase().contains(searchTerm)) ||
                               (email != null && email.toLowerCase().contains(searchTerm));
                    })
                    .collect(Collectors.toList());
            }
            
            response.put("success", true);
            response.put("data", allUsers);
            response.put("total", allUsers.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取用户列表失败", e);
            response.put("success", false);
            response.put("message", "获取用户列表失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取用户详细信息
     */
    @GetMapping("/users/{userId}")
    public ResponseEntity<Map<String, Object>> getUserDetails(
            @PathVariable Long userId, 
            @RequestParam(required = false) String userType) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 根据userType参数决定查询哪个表
            if ("ADMIN".equals(userType) || "ROOT_ADMIN".equals(userType)) {
                // 管理员用户，从Admin表查找
                Optional<Admin> adminOpt = adminRepository.findById(userId);
                
                if (adminOpt.isPresent()) {
                    Admin admin = adminOpt.get();
                    
                    // 创建与User类似的数据结构
                    Map<String, Object> adminData = new HashMap<>();
                    adminData.put("userId", admin.getAdminId());
                    adminData.put("username", admin.getUsername());
                    adminData.put("password", "***"); // 隐藏密码
                    adminData.put("email", admin.getEmail());
                    adminData.put("createdAt", admin.getCreatedAt());
                    adminData.put("updatedAt", admin.getUpdatedAt());
                    adminData.put("isActive", true); // 管理员默认激活
                    
                    // 设置管理员角色
                    List<String> roles = new ArrayList<>();
                    if ("system".equals(admin.getUsername())) {
                        roles.add("ROOT_ADMIN");
                        adminData.put("admin", true);
                        adminData.put("rootAdmin", true);
                    } else {
                        roles.add("ADMIN");
                        adminData.put("admin", true);
                        adminData.put("rootAdmin", false);
                    }
                    adminData.put("roles", roles);
                    
                    // 管理员的文件统计为空
                    Map<String, Object> fileStats = new HashMap<>();
                    fileStats.put("totalFiles", 0);
                    fileStats.put("activeFiles", 0);
                    fileStats.put("deletedFiles", 0);
                    fileStats.put("totalSize", 0L);
                    fileStats.put("deletedSize", 0L);
                    fileStats.put("activeSize", 0L);
                    
                    Map<String, Object> userDetails = new HashMap<>();
                    userDetails.put("user", adminData);
                    userDetails.put("fileStats", fileStats);
                    
                    response.put("success", true);
                    response.put("data", userDetails);
                    
                    return ResponseEntity.ok(response);
                }
            } else {
                // 普通用户或未指定类型，从User表查找
                Optional<User> userOpt = userService.findById(userId);
                if (userOpt.isPresent()) {
                    User user = userOpt.get();
                    user.setPassword("***"); // 隐藏密码
                    
                    // 获取用户文件统计
                    FileService.UserFileStats fileStats = fileService.getUserFileStats(userId);
                    
                    Map<String, Object> userDetails = new HashMap<>();
                    userDetails.put("user", user);
                    userDetails.put("fileStats", fileStats);
                    
                    response.put("success", true);
                    response.put("data", userDetails);
                    
                    return ResponseEntity.ok(response);
                }
                
                // 如果User表没有找到，且没有指定userType，尝试从Admin表查找
                if (userType == null) {
                    Optional<Admin> adminOpt = adminRepository.findById(userId);
                    if (adminOpt.isPresent()) {
                        Admin admin = adminOpt.get();
                        
                        // 创建与User类似的数据结构
                        Map<String, Object> adminData = new HashMap<>();
                        adminData.put("userId", admin.getAdminId());
                        adminData.put("username", admin.getUsername());
                        adminData.put("password", "***"); // 隐藏密码
                        adminData.put("email", admin.getEmail());
                        adminData.put("createdAt", admin.getCreatedAt());
                        adminData.put("updatedAt", admin.getUpdatedAt());
                        adminData.put("isActive", true); // 管理员默认激活
                        
                        // 设置管理员角色
                        List<String> roles = new ArrayList<>();
                        if ("system".equals(admin.getUsername())) {
                            roles.add("ROOT_ADMIN");
                            adminData.put("admin", true);
                            adminData.put("rootAdmin", true);
                        } else {
                            roles.add("ADMIN");
                            adminData.put("admin", true);
                            adminData.put("rootAdmin", false);
                        }
                        adminData.put("roles", roles);
                        
                        // 管理员的文件统计为空
                        Map<String, Object> fileStats = new HashMap<>();
                        fileStats.put("totalFiles", 0);
                        fileStats.put("activeFiles", 0);
                        fileStats.put("deletedFiles", 0);
                        fileStats.put("totalSize", 0L);
                        fileStats.put("deletedSize", 0L);
                        fileStats.put("activeSize", 0L);
                        
                        Map<String, Object> userDetails = new HashMap<>();
                        userDetails.put("user", adminData);
                        userDetails.put("fileStats", fileStats);
                        
                        response.put("success", true);
                        response.put("data", userDetails);
                        
                        return ResponseEntity.ok(response);
                    }
                }
            }
            
            // 如果都没有找到
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.badRequest().body(response);
            
        } catch (Exception e) {
            logger.error("获取用户详细信息失败", e);
            response.put("success", false);
            response.put("message", "获取用户详细信息失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 禁用/启用用户
     */
    @PutMapping("/users/{userId}/status")
    public ResponseEntity<Map<String, Object>> toggleUserStatus(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Optional<User> userOpt = userService.findById(userId);
            if (!userOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            User user = userOpt.get();
            boolean newStatus = !user.getIsActive();
            boolean success = userService.setUserActiveStatus(userId, newStatus);
            
            if (success) {
                response.put("success", true);
                response.put("message", newStatus ? "用户已启用" : "用户已禁用");
                response.put("isActive", newStatus);
                logger.info("管理员{}用户: userId={}, newStatus={}", 
                    newStatus ? "启用" : "禁用", userId, newStatus);
            } else {
                response.put("success", false);
                response.put("message", "更新用户状态失败");
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("切换用户状态失败", e);
            response.put("success", false);
            response.put("message", "切换用户状态失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 重置用户密码
     */
    @PostMapping("/users/{userId}/reset-password")
    public ResponseEntity<Map<String, Object>> resetUserPassword(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Optional<User> userOpt = userService.findById(userId);
            if (!userOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            String newPassword = userService.resetPassword(userId);
            
            if (newPassword != null) {
                response.put("success", true);
                response.put("message", "密码重置成功");
                response.put("newPassword", newPassword);
                logger.info("管理员重置用户密码: userId={}", userId);
            } else {
                response.put("success", false);
                response.put("message", "密码重置失败");
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("重置用户密码失败", e);
            response.put("success", false);
            response.put("message", "重置用户密码失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/users/{userId}")
    public ResponseEntity<Map<String, Object>> deleteUser(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Optional<User> userOpt = userService.findById(userId);
            if (!userOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            User user = userOpt.get();
            // 检查是否为管理员
            if (user.isAdmin()) {
                response.put("success", false);
                response.put("message", "不能删除管理员用户");
                return ResponseEntity.badRequest().body(response);
            }
            
            boolean success = userService.deleteUser(userId);
            
            if (success) {
                response.put("success", true);
                response.put("message", "用户删除成功");
                logger.info("管理员删除用户: userId={}, username={}", userId, user.getUsername());
            } else {
                response.put("success", false);
                response.put("message", "用户删除失败");
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("删除用户失败", e);
            response.put("success", false);
            response.put("message", "删除用户失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取用户活动记录
     */
    @GetMapping("/users/{userId}/activities")
    public ResponseEntity<Map<String, Object>> getUserActivities(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 获取用户最近活动记录
            List<Map<String, Object>> activities = userService.getUserRecentActivities(userId);
            
            response.put("success", true);
            response.put("data", activities);
            response.put("total", activities.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取用户活动记录失败", e);
            response.put("success", false);
            response.put("message", "获取用户活动记录失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取用户文件列表
     */
    @GetMapping("/users/{userId}/files")
    public ResponseEntity<Map<String, Object>> getUserFiles(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<FileInfo> files = fileService.getUserFiles(userId);
            
            response.put("success", true);
            response.put("data", files);
            response.put("total", files.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取用户文件列表失败", e);
            response.put("success", false);
            response.put("message", "获取用户文件列表失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    // ===========================================
    // 日志管理相关接口
    // ===========================================

    /**
     * 获取系统日志概览
     */
    @GetMapping("/logs/overview")
    public ResponseEntity<Map<String, Object>> getLogOverview() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Map<String, Object> stats = logService.getSystemOperationStats();
            
            response.put("success", true);
            response.put("data", stats);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取系统日志概览失败", e);
            response.put("success", false);
            response.put("message", "获取系统日志概览失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取用户操作日志
     */
    @GetMapping("/logs/user-operations")
    public ResponseEntity<Map<String, Object>> getUserOperationLogs(
            @RequestParam(required = false) Long userId,
            @RequestParam(defaultValue = "50") int limit) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<UserOperationLog> logs;
            if (userId != null) {
                logs = logService.getUserOperationLogs(userId, limit);
            } else {
                logs = logService.getRecentUserOperationLogs(limit);
            }
            
            response.put("success", true);
            response.put("data", logs);
            response.put("total", logs.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取用户操作日志失败", e);
            response.put("success", false);
            response.put("message", "获取用户操作日志失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取文件操作日志
     */
    @GetMapping("/logs/file-operations")
    public ResponseEntity<Map<String, Object>> getFileOperationLogs(
            @RequestParam(required = false) Long fileId,
            @RequestParam(defaultValue = "50") int limit) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<FileOperationLog> logs;
            if (fileId != null) {
                logs = logService.getFileOperationLogs(fileId);
            } else {
                logs = logService.getRecentFileOperationLogs(limit);
            }
            
            // 转换为DTO以避免lazy loading问题
            List<Map<String, Object>> logDtos = logs.stream().map(this::buildFileOperationLogResponse).collect(Collectors.toList());
            
            response.put("success", true);
            response.put("data", logDtos);
            response.put("total", logDtos.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取文件操作日志失败", e);
            response.put("success", false);
            response.put("message", "获取文件操作日志失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 构建文件操作日志响应
     */
    private Map<String, Object> buildFileOperationLogResponse(FileOperationLog log) {
        Map<String, Object> result = new HashMap<>();
        result.put("logId", log.getLogId());
        result.put("userId", log.getUserId());
        result.put("fileId", log.getFileId());
        result.put("operationType", log.getOperationType());
        result.put("operationDetails", log.getOperationDetails());
        result.put("operationTime", log.getOperationTime());
        
        // 安全地获取用户信息
        if (log.getUser() != null) {
            result.put("username", log.getUser().getUsername());
        }
        
        // 安全地获取文件信息
        if (log.getFile() != null) {
            result.put("fileName", log.getFile().getOriginalFilename());
            result.put("fileSize", log.getFile().getFileSize());
        }
        
        return result;
    }

    /**
     * 获取最近活动日志（用于仪表板）
     */
    @GetMapping("/logs/recent-activities")
    public ResponseEntity<Map<String, Object>> getRecentActivities(
            @RequestParam(defaultValue = "20") int limit) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<UserOperationLog> userLogs = logService.getRecentUserOperationLogs(limit / 2);
            List<FileOperationLog> fileLogs = logService.getRecentFileOperationLogs(limit / 2);
            
            Map<String, Object> activities = new HashMap<>();
            activities.put("userOperations", userLogs);
            activities.put("fileOperations", fileLogs);
            
            response.put("success", true);
            response.put("data", activities);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取最近活动日志失败", e);
            response.put("success", false);
            response.put("message", "获取最近活动日志失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取热门文件
     */
    @GetMapping("/logs/hot-files")
    public ResponseEntity<Map<String, Object>> getHotFiles(
            @RequestParam(defaultValue = "10") int limit) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<Object[]> hotFiles = logService.getHotFiles(limit);
            
            response.put("success", true);
            response.put("data", hotFiles);
            response.put("total", hotFiles.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取热门文件失败", e);
            response.put("success", false);
            response.put("message", "获取热门文件失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 清理过期日志
     */
    @PostMapping("/logs/cleanup")
    public ResponseEntity<Map<String, Object>> cleanupLogs(
            @RequestParam(defaultValue = "30") int daysToKeep) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            logService.cleanupOldLogs(daysToKeep);
            
            response.put("success", true);
            response.put("message", "日志清理任务已执行");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("清理日志失败", e);
            response.put("success", false);
            response.put("message", "清理日志失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取日志按时间范围
     */
    @GetMapping("/logs/by-time-range")
    public ResponseEntity<Map<String, Object>> getLogsByTimeRange(
            @RequestParam String startTime,
            @RequestParam String endTime,
            @RequestParam(defaultValue = "user") String logType) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            LocalDateTime start = LocalDateTime.parse(startTime);
            LocalDateTime end = LocalDateTime.parse(endTime);
            
            Object logs;
            if ("user".equals(logType)) {
                logs = logService.getUserOperationLogsByTimeRange(start, end);
            } else if ("file".equals(logType)) {
                logs = logService.getFileOperationLogsByTimeRange(start, end);
            } else {
                response.put("success", false);
                response.put("message", "无效的日志类型");
                return ResponseEntity.badRequest().body(response);
            }
            
            response.put("success", true);
            response.put("data", logs);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取时间范围日志失败", e);
            response.put("success", false);
            response.put("message", "获取时间范围日志失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取上传日志
     */
    @GetMapping("/upload-logs")
    public ResponseEntity<Map<String, Object>> getUploadLogs() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 获取所有UPLOAD类型的文件操作日志
            List<FileOperationLog> uploadLogs = logService.getFileOperationLogsByType("UPLOAD", 100);
            
            // 转换为响应格式
            List<Map<String, Object>> logResponses = uploadLogs.stream()
                    .map(this::buildUploadLogResponse)
                    .collect(java.util.stream.Collectors.toList());
            
            response.put("success", true);
            response.put("data", logResponses);
            response.put("total", logResponses.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取上传日志失败", e);
            response.put("success", false);
            response.put("message", "获取上传日志失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取下载日志
     */
    @GetMapping("/download-logs")
    public ResponseEntity<Map<String, Object>> getDownloadLogs() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 获取所有DOWNLOAD类型的文件操作日志
            List<FileOperationLog> downloadLogs = logService.getFileOperationLogsByType("DOWNLOAD", 100);
            
            // 转换为响应格式
            List<Map<String, Object>> logResponses = downloadLogs.stream()
                    .map(this::buildDownloadLogResponse)
                    .collect(java.util.stream.Collectors.toList());
            
            response.put("success", true);
            response.put("data", logResponses);
            response.put("total", logResponses.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取下载日志失败", e);
            response.put("success", false);
            response.put("message", "获取下载日志失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 构建上传日志响应
     */
    private Map<String, Object> buildUploadLogResponse(FileOperationLog log) {
        Map<String, Object> data = new HashMap<>();
        data.put("logId", log.getLogId());
        data.put("operationType", log.getOperationType());
        data.put("operationTime", log.getOperationTime());
        data.put("operationDetails", log.getOperationDetails());
        data.put("userId", log.getUserId());
        data.put("fileId", log.getFileId());
        
        // 获取用户信息
        try {
            Optional<User> userOpt = userService.findById(log.getUserId());
            if (userOpt.isPresent()) {
                data.put("uploaderName", userOpt.get().getUsername());
            } else {
                data.put("uploaderName", "未知用户");
            }
        } catch (Exception e) {
            data.put("uploaderName", "未知用户");
        }
        
        // 获取文件信息
        if (log.getFileId() != null) {
            try {
                Optional<FileInfo> fileOpt = fileService.getFileById(log.getFileId());
                if (fileOpt.isPresent()) {
                    FileInfo fileInfo = fileOpt.get();
                    data.put("originalFilename", fileInfo.getOriginalFilename());
                    data.put("fileSizeFormatted", fileInfo.getReadableFileSize());
                    data.put("userTags", fileInfo.getUserTags());
                    data.put("isEncrypted", fileInfo.getIsEncrypted());
                } else {
                    data.put("originalFilename", "文件已删除");
                    data.put("fileSizeFormatted", "未知");
                    data.put("userTags", "");
                    data.put("isEncrypted", false);
                }
            } catch (Exception e) {
                data.put("originalFilename", "未知文件");
                data.put("fileSizeFormatted", "未知");
                data.put("userTags", "");
                data.put("isEncrypted", false);
            }
        } else {
            data.put("originalFilename", "未知文件");
            data.put("fileSizeFormatted", "未知");
            data.put("userTags", "");
            data.put("isEncrypted", false);
        }
        
        return data;
    }

    /**
     * 构建下载日志响应
     */
    private Map<String, Object> buildDownloadLogResponse(FileOperationLog log) {
        Map<String, Object> data = new HashMap<>();
        data.put("logId", log.getLogId());
        data.put("operationType", log.getOperationType());
        data.put("operationTime", log.getOperationTime());
        data.put("operationDetails", log.getOperationDetails());
        data.put("userId", log.getUserId());
        data.put("fileId", log.getFileId());
        
        // 获取用户信息
        try {
            Optional<User> userOpt = userService.findById(log.getUserId());
            if (userOpt.isPresent()) {
                data.put("username", userOpt.get().getUsername());
            } else {
                data.put("username", "未知用户");
            }
        } catch (Exception e) {
            data.put("username", "未知用户");
        }
        
        // 获取文件信息
        if (log.getFileId() != null) {
            try {
                Optional<FileInfo> fileOpt = fileService.getFileById(log.getFileId());
                if (fileOpt.isPresent()) {
                    FileInfo fileInfo = fileOpt.get();
                    data.put("filename", fileInfo.getOriginalFilename());
                    data.put("fileSize", fileInfo.getReadableFileSize());
                } else {
                    data.put("filename", "文件已删除");
                    data.put("fileSize", "未知");
                }
            } catch (Exception e) {
                data.put("filename", "未知文件");
                data.put("fileSize", "未知");
            }
        } else {
            data.put("filename", "未知文件");
            data.put("fileSize", "未知");
        }
        
        return data;
    }

    /**
     * 构建管理员文件信息响应（包含上传者信息）
     */
    private Map<String, Object> buildAdminFileInfoResponse(FileInfo fileInfo) {
        Map<String, Object> data = new HashMap<>();
        data.put("fileId", fileInfo.getFileId());
        data.put("originalFilename", fileInfo.getOriginalFilename());
        data.put("fileSize", fileInfo.getFileSize());
        data.put("fileSizeFormatted", fileInfo.getReadableFileSize());
        data.put("userTags", fileInfo.getUserTags());
        data.put("isEncrypted", fileInfo.getIsEncrypted());
        data.put("isDeleted", fileInfo.getIsDeleted());
        data.put("createdAt", fileInfo.getCreatedAt());
        data.put("updatedAt", fileInfo.getUpdatedAt());
        data.put("userId", fileInfo.getUserId());
        
        // 获取上传者信息
        try {
            Optional<User> userOpt = userService.findById(fileInfo.getUserId());
            if (userOpt.isPresent()) {
                data.put("uploaderName", userOpt.get().getUsername());
            } else {
                data.put("uploaderName", "未知用户");
            }
        } catch (Exception e) {
            data.put("uploaderName", "未知用户");
        }
        
        return data;
    }
}